package com.ignou.mca.evote;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ignou.mca.datasource.DataBaseUtilities;
import com.ignou.mca.datasource.Encryption;
import com.ignou.mca.beans.CandidatesFormBean;
import com.ignou.mca.beans.Message;
import com.ignou.mca.beans.VotersFormBean;
import com.ignou.mca.util.SessionUtil;
import org.apache.log4j.Logger;
import org.eclipse.jdt.internal.compiler.ast.PostfixExpression;

public class AddCandidates extends HttpServlet implements Servlet {

	DataBaseUtilities dbu = null;
	Connection con = null;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		dbu = new DataBaseUtilities();
		String candidateName = req.getParameter("candidateName");
		String address1 = req.getParameter("address1");
		String address2 = req.getParameter("address2");
		String city = req.getParameter("city");
		String state = req.getParameter("state");
		String country = req.getParameter("country");
		String phno = req.getParameter("phno");
		String email = req.getParameter("email");
		String position = req.getParameter("position");
		String party = req.getParameter("party");
		String personPictureURL = req.getParameter("personPictureURL");

		if(personPictureURL == "")
		{
			personPictureURL = "profile_icon.jpg";
		}
		
		Message message = new Message();
		CandidatesFormBean candidates = new CandidatesFormBean();
		candidates.setCandidateName(candidateName);
		candidates.setAddress1(address1);
		candidates.setAddress2(address2);
		candidates.setCity(city);
		candidates.setState(state);
		candidates.setCountry(country);
		candidates.setPhno(phno);
		candidates.setEmail(email);
		candidates.setPositionID(Integer.parseInt(position));
		candidates.setPartyID(Integer.parseInt(party));
		candidates.setPicURL(personPictureURL);

		HttpSession session = req.getSession(true);
		session.setAttribute("Message", message);
		req.setAttribute("Candidates", candidates);
		ServletContext context = getServletContext();

		if (!SessionUtil.validateSession(req, resp)) {
			resp.sendRedirect(req.getServletPath()+ "/Login.jsp");
			return;
		}

		if ((candidateName.equalsIgnoreCase(""))
				|| (address1.equalsIgnoreCase(""))
				|| (address2.equalsIgnoreCase(""))
				|| (city.equalsIgnoreCase("")) || (state.equalsIgnoreCase(""))
				|| (country.equalsIgnoreCase(""))
				|| (position.equalsIgnoreCase(""))
				|| (party.equalsIgnoreCase("")) || (phno.equalsIgnoreCase(""))) {
			message.setMessage("You have not completed all the fields.Please complete all mandatory fields.");
			context.getRequestDispatcher("/AddCandidates.jsp").forward(req,
					resp);
		} else {
			String isSuccess = addCandidates(candidates);
			if (isSuccess.equalsIgnoreCase("Success")) {
				context.getRequestDispatcher("/AdminMenu.jsp").forward(req,
						resp);
			} else 	if (isSuccess.equalsIgnoreCase("AlreadyExists")) {
				req.setAttribute("ErrorMessage",
				"Candidate already exists for this position for  party you have mentioned.");
				context.getRequestDispatcher("/TransactionFailed.jsp").forward(
						req, resp);
			}else {
				req.setAttribute("ErrorMessage",
								"Error in connecting to database. Please try again later.");
				context.getRequestDispatcher("/TransactionFailed.jsp").forward(
						req, resp);
			}
		}
	}

	public String addCandidates(CandidatesFormBean ufb) {
		if (con==null)con =  dbu.getConnection();
		String query = "insert into candidates (CandidateName,Address1,"
				+ "Address2,city,state,country,PositionID,PartyID,phoneNumber,email,candidatePic)"
				+ " values(?,?,?,?,?,?,?,?,?,?,?)";
		if (checkCandidate(ufb.getCandidateName(),ufb.getPositionID(),ufb.getPartyID())) {
			return "AlreadyExists";
		}

		try {
			PreparedStatement pst = con.prepareStatement(query);
			pst.setString(1, ufb.getCandidateName());
			pst.setString(2, ufb.getAddress1());
			pst.setString(3, ufb.getAddress2());
			pst.setString(4, ufb.getCity());
			pst.setString(5, ufb.getState());
			pst.setString(6, ufb.getCountry());
			pst.setInt(7, ufb.getPositionID());
			pst.setInt(8, ufb.getPartyID());
			pst.setString(9, ufb.getPhno());
			pst.setString(10, ufb.getEmail());
			pst.setString(11, ufb.getPicURL());

			int i = pst.executeUpdate();

			if (i == 1) {
				return "Success";
			}else
			{
				return "Failure";
			}

		} catch (Exception e) {

		}
		return "Failure";
	}
	
	public boolean checkCandidate(String candidate,int partyId,int positionId)
	{
		if (con==null) con = dbu.getConnection();
		try {
			Statement st = con.createStatement();
			ResultSet rs = st.executeQuery("select candidateName from candidates where positionID="+positionId+" AND partyID="+partyId);
			
			while(rs.next())
			{
				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
	}
}